package unclassified.medium;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RangeFrequencyQueries_5186 {
    Map<Integer, List<Integer>> map;
    public RangeFrequencyQueries_5186(int[] arr) {
        map = new HashMap<>();
        for (int i = 0; i < arr.length; i++) {
            map.computeIfAbsent(arr[i], k -> new ArrayList<>()).add(i);
        }
    }

    public int query(int left, int right, int value) {
        List<Integer> list = map.get(value);
        int res = 0;
        if (list == null) {
            return res;
        }
        if (left > list.get(list.size() - 1)) {
            return res;
        }
        if (right < list.get(0)) {
            return res;
        }
        int l = 0, r = list.size();
        int leftBorder = 0, rightBorder = 0;
        while(l < r) {
            int mid = l + (r - l) / 2;
            //[left, mid) or [mid + 1, right)
            if (list.get(mid) < left) {
                l = mid + 1;
            } else if(list.get(mid) >= left) {
                r = mid;
            }
        }
        leftBorder = l;
        l = 0;
        r = list.size();
        while(l < r) {
            int mid = l + (r - l) / 2;
            //(left, mid] 或 (mid, right]
            if(list.get(mid) <= right) {
                l = mid + 1;
            } else if (list.get(mid) > right) {
                r = mid;
            }
        }
        rightBorder = l;
        return rightBorder - leftBorder;
    }
}
